package prj.common.web.renderer;

import java.io.IOException;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import prj.common.service.CaptchaService;
import prj.common.web.component.CaptchaComponent;

import com.sun.faces.renderkit.html_basic.ImageRenderer;

public class CaptchaRenderer extends ImageRenderer {
	private static final String DEFAULT_IMG_WIDTH = "120";
	private static final String DEFAULT_IMG_HEIGHT = "60";
    @Override
    public void encodeBegin(FacesContext context, UIComponent component)
          throws IOException {

        super.encodeBegin(context, component);
        CaptchaComponent cc = (CaptchaComponent)component;

        String captcha = CaptchaService.getCaptchaString();
        String random = CaptchaService.getCaptchaString(); //Get a different string for form
        String w = (cc.getWidth() != null) ? cc.getWidth() : DEFAULT_IMG_WIDTH;
        String h = (cc.getHeight() != null) ? cc.getHeight() : DEFAULT_IMG_HEIGHT;
        
        String url = "/" + random + ".captcha?field=" + cc.getCaptchaField() + "&w=" + w + "&h=" + h;
        cc.setUrl(url);
        
        //Save the captcha in session
        ((HttpSession)context.getExternalContext().getSession(true)).setAttribute(CaptchaService.CAPTCHA_SESSION_KEY + cc.getCaptchaField(), captcha);
    }
}
